package com.czh.framework.security.web.service;

import com.czh.framework.security.exception.TokenExpiredException;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class TokenService {

    private static final String secret = "abc";

    public static final Integer MINUTE = 60;



    public static String createToken (Map<String , Object> claims) {
        String compact = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, secret.getBytes(StandardCharsets.UTF_8))
                .setClaims(claims).compact();
        return compact;
    }

    public static Map<String,Object> parseToken(String token) {
        Jwt parse = null;
        try {
            parse = Jwts.parser().setSigningKey(secret.getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token);
        }catch (Exception e) {
            throw new TokenExpiredException("token 失效");
        }

        return (Map<String,Object>)parse.getBody();
    }

    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<>();
        map.put("key","uid");//eyJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ1aWQifQ.7RIDYsWMM9MJppru0LbagOnvt8scSUu0VXcaedT4CYQ
        System.out.println(createToken(map));
        System.out.println(parseToken("eyJhbGciOiJIUzI1NiJ9.eyJrZXkiOiJ1aWQifQ.7RIDYsWMM9MJppru0LbagOnvt8scSUu0VXcaedT4CYQ"));
    }

}
